package org.bigtree.example.common.frame.handles;

import org.bigtree.example.common.utils.JsonUtils;
import org.bigtree.example.common.webapi.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回响应体处理器
 *
 * @author bigTree
 * @since 2025/4/28
 */
@RestControllerAdvice
public class GeneralResponseBodyHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return !(returnType.getGenericParameterType() instanceof ResponseResult);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseResult<?> resp = ResponseResult.ok(body);
        if (body instanceof String) {
            return JsonUtils.toJson(resp);
        }
        return resp;
    }
}
